package com.example.springboot.ytest.ytest;


import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Base64;
/**
 * 联通回调AES加解密工具类（加密已偏移18个字节，可模拟联通加密数据）
 * @author yeyi
 * @date 2020/11/18 14:26
 **/
public class AesDecryptUtil {

    private static final String KEY_ALGORITHM = "AES";
    // AES/CBC/PKCS7Padding:算法/模式/补码方式
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";


    public static String aesDecrypt(String content, String encryptKey) {

        byte[] contentByteArray;
        byte[] base64decryptedContentByteArray;
        byte[] decryptedContentByteArray;
        String decryptedMsg;

        // Base64 decryption
        try {
            contentByteArray = content.getBytes("utf-8");
            base64decryptedContentByteArray = Base64.getDecoder().decode(contentByteArray);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        // AES decryption
        try {
            byte[] rawKey = encryptKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(rawKey, KEY_ALGORITHM);
            // 这个地方调用BouncyCastleProvider, 让java支持PKCS7Padding
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            // 初始向量iv
            byte[] ivbytes = new byte[16];
            for (int i = 0; i < 16; i++) {
                ivbytes[i] = rawKey[i];
            }
            IvParameterSpec iv = new IvParameterSpec(ivbytes);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            decryptedContentByteArray = cipher.doFinal(base64decryptedContentByteArray);
            int msgLength = decryptedContentByteArray.length - 8 - 10;
            byte[] msg = new byte[msgLength];
            System.arraycopy(decryptedContentByteArray, 18, msg, 0,msgLength);
            decryptedMsg = new String(msg, "utf-8");
            return decryptedMsg;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encode(String content, String password){
        try {

            byte[] passwordBytes = password.getBytes("UTF8");
            byte[] contents = content.getBytes("UTF8");
            int msgLength =  contents.length;
            byte[] padding = new byte[18 + msgLength];

            System.arraycopy(contents, 0, padding, 18, msgLength);
            // IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
            byte[] ivbytes = new byte[16];
            for (int i = 0; i < 16; i++) {
                ivbytes[i] = passwordBytes[i];
            }
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivbytes);
            SecretKeySpec skeySpec = new SecretKeySpec(passwordBytes, KEY_ALGORITHM);
            /**
             * 这个地方调用BouncyCastleProvider
             *让java支持PKCS7Padding
             */
            Security.addProvider(new BouncyCastleProvider());
            // Cipher is not thread safe
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);

            String encrypedValue = Base64.getEncoder().encodeToString(cipher.doFinal(padding));
            return encrypedValue;

        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return "";
    }
}
